package com.cynteka.cyfoman.core;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * User: ukman
 * Date: 21.07.2011
 * Time: 10:33:10
 */
public class FolderScanner implements Runnable {
    private File scanFolder;
    private boolean cont = true;
    private boolean started = false;
    private int timeout = 1000;
    private Set<File> scanedFiles = new HashSet<File>();
    List<FolderChangedListener> listeners = new ArrayList<FolderChangedListener>();
    private Logger logger = Logger.getLogger(FolderScanner.class.getName());

    public FolderScanner() {

    }

    public FolderScanner(File scanFolder) {
        this.scanFolder = scanFolder;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public void setScanFolder(File scanFolder) {
        this.scanFolder = scanFolder;
    }

    public File getScanFolder() {
        return scanFolder;
    }

    public synchronized void start() {
        if (started)
            throw new IllegalStateException("Service is already started");
        started = true;
        Thread t = new Thread(this);
        t.setName("Folder scanner (" + scanFolder + ")");
        t.setDaemon(true);
        t.start();
    }

    public synchronized void stop() {
        cont = false;
    }

    @Override
    public void run() {
        synchronized (this) {
            while (cont) {
                File[] files = scanFolder.listFiles();
                Set<File> newFiles = new HashSet<File>();
                for (File f : files) {

                    if (!(f.isDirectory() && (f.getName().equals(".") || f.getName().equals("..")))) {
                        if (!scanedFiles.contains(f)) {
                            newFiles.add(f);
                        }
                    }
                }
                if (!newFiles.isEmpty()) {
                    scanedFiles.addAll(newFiles);
                    fireChangeListeners(newFiles.toArray(new File[newFiles.size()]));

                }
                try {
                    wait(timeout);
                } catch (InterruptedException e) {
                    logger.log(Level.SEVERE, "Error waiting", e);
                }
            }
            started = false;
        }
    }

    public void addChangeListener(FolderChangedListener listener) {
        listeners.add(listener);
    }

    public void removeChangeListener(FolderChangedListener listener) {
        listeners.remove(listener);
    }

    protected void fireChangeListeners(File[] newFiles) {
        for (FolderChangedListener listener : listeners) {
            listener.folderChanged(newFiles);
        }
    }
}
